﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.ComponentModel;
using Terralever.Facebook.UI.Design;

namespace Terralever.Facebook.UI.FbmlControls
{
    /// <summary>
    /// Represents the base functionality for a control that can render child content.
    /// </summary>
    [PersistChildren(false)]
    [ParseChildren(ChildrenAsProperties = true)]
    [Designer("Terralever.Facebook.UI.Design.FbmlControls.ContentDisplayControlDesigner, " + Constants.DESIGNER_LIB)]
    public abstract class ContentDisplayControl : FbmlControl
    {
        private ITemplate m_contentTemplate;
        private LogicTestTemplateContainer m_contentContainer;

        /// <summary>
        /// Gets or sets the template displayed when the control's requirements are met.
        /// </summary>
        [Browsable(false)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DefaultValue(null)]
        [TemplateInstance(TemplateInstance.Single)]
        [TemplateContainer(typeof(LogicTestTemplateContainer))]
        [FbmlRequired(IsRequired = true)]
        public ITemplate ContentTemplate
        {
            get { return m_contentTemplate; }
            set
            {
                m_contentTemplate = value;
                if (m_contentTemplate != null)
                    CreateContents();
            }
        }

        /// <inheritdoc />
        protected override void Render(HtmlTextWriter writer)
        {
            if (m_contentContainer == null)
                throw new RequiredFbmlAttributeNotSetException("The <ContentTemplate> template is missing and is required.");

            CreateContents();

            AddAttributesToRender(writer);
            writer.RenderBeginTag(ElementName);
            m_contentContainer.RenderControl(writer);
            writer.RenderEndTag();
        }

        private void CreateContents()
        {
            ClearContents();

            if (m_contentContainer == null)
            {
                m_contentContainer = new LogicTestTemplateContainer(this);
                if (m_contentTemplate != null)
                {
                    m_contentTemplate.InstantiateIn(m_contentContainer);
                }
                this.Controls.Add(m_contentContainer);
            }
            else if (m_contentTemplate != null)
            {
                this.m_contentTemplate.InstantiateIn(this.m_contentContainer);
            }
        }

        private void ClearContents()
        {
            if (m_contentContainer != null)
                m_contentContainer.Controls.Clear();

            m_contentContainer = null;

            Controls.Clear();
        }
    }
}

